<template>
  <div>
    <el-tree
      ref="refTree"
      node-key="id"
      :data="list"
      :props="{label:'name'}"
      :show-checkbox="true"
      :default-expand-all="true"
      check-strictly
    />
    <div>
      <el-button @click="hCancel">取消</el-button>
      <el-button @click="hSave">确定</el-button>
      {{ curId }}
    </div>
  </div>
</template>
<script>

import { getRoleDetail, assignPerm } from '@/api/settings'
import { array2Tree } from '@/utils/index'
import { getPermissionList } from '@/api/permissions'
export default {
  props: {
    curId: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      list: []
    }
  },
  created() {
    this.loadPermissionList()

    // 调用接口获取当前角色具备的权限
    // this.loadPermission()
  },
  methods: {
    async hSave() {
      // 1. 获取选中的节点
      const permIds = this.$refs.refTree.getCheckedKeys()

      // 2. 调用接口
      await assignPerm({ id: this.curId, permIds: permIds })

      this.$message.success('保存成功')

      // 3. 通知父组件关闭弹层
      this.$emit('success')
    },
    async loadPermission() {
      // 当前角色具体的权限点
      const res = await getRoleDetail(this.curId)
      console.log('res', res)
      // 数据回填
      // 让树状节点选中指定的元素
      this.$refs.refTree.setCheckedKeys(res.data.permIds)
    },
    async loadPermissionList() {
      const res = await getPermissionList()
      // 转成树
      this.list = array2Tree(res.data, '0')
    },
    hCancel() {
      this.$emit('close')
    }
  }
}
</script>
